#include <muduo/net/TcpServer.h> //包含头文件
#include <muduo/net/EventLoop.h>
#include <iostream>
#include <functional>
using namespace std;
using namespace muduo;
using namespace muduo::net;

class ChatServer
{
public:
    ChatServer(EventLoop *loop,
               const InetAddress &listenAddr,
               const string &nameArg) : _server(loop, listenAddr, nameArg), _loop(loop)
    {
        // 注册连接事件回调
        _server.setConnectionCallback(std::bind(&ChatServer::onConnection, this, placeholders::_1));
        // 注册读写事件回调
        _server.setMessageCallback(std::bind(&ChatServer::onMessage, this, placeholders::_1, placeholders::_2, placeholders::_3));
        // 设置线程数量
        _server.setThreadNum(4);
    }
    void start(){
        _server.start();
    }

private:
    // 处理用户的连接
    void onConnection(const TcpConnectionPtr &conn)
    {
        cout << conn->peerAddress().toIpPort() << "->" << conn->localAddress().toIpPort() << "is" << (conn->connected() ? "UP" : "DOWN") << endl;
    }
    // 处理用户的读写事件
    void onMessage(const TcpConnectionPtr &conn, Buffer *buffer, Timestamp time)
    {
        string buf=buffer->retrieveAllAsString();
        cout<<"recv data:"<<buf<<time.toString()<<endl;
        conn->send(buf);
    }
    TcpServer _server;
    EventLoop *_loop;
};
int main(){
    EventLoop *loop=new EventLoop();
    InetAddress addr("127.0.0.1",8080);
    ChatServer _ser(loop,addr,"ChatServer");
    _ser.start();
    loop->loop();
} 